/*
 * pi3's Linux kernel Runtime Guard
 *
 * Component:
 *  - Intercept unshare syscall
 *
 * Notes:
 *  - None
 *
 * Caveats:
 *  - None
 *
 * Timeline:
 *  - Created: 05.XII.2017
 *
 * Author:
 *  - Adam 'pi3' Zabrocki (http://pi3.com.pl)
 *
 */

#include "../../../../p_lkrg_main.h"


char p_sys_unshare_kretprobe_state = 0;

static struct kretprobe p_sys_unshare_kretprobe = {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(4,17,0)
    .kp.symbol_name = "ksys_unshare",
#else
    .kp.symbol_name = "sys_unshare",
#endif
    .handler = p_sys_unshare_ret,
    .entry_handler = p_sys_unshare_entry,
    .data_size = sizeof(struct p_sys_unshare_data),
    /* Probe up to 40 instances concurrently. */
    .maxactive = 40,
};


int p_sys_unshare_entry(struct kretprobe_instance *p_ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   p_ed_enforce_validation();

   p_tasks_write_lock(&p_flags);
   if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
#ifdef P_LKRG_TASK_OFF_DEBUG
      p_debug_off_flag_off(p_tmp, 59);
#endif
      // This process is on the ED list - set temporary 'disable' flag!
      p_set_ed_process_off(p_tmp);
   }
   p_tasks_write_unlock(&p_flags);

   return 0;
}


int p_sys_unshare_ret(struct kretprobe_instance *ri, struct pt_regs *p_regs) {

   struct p_ed_process *p_tmp;
   unsigned long p_flags;

   p_debug_kprobe_log(
          "unshare returned value => %ld comm[%s] Pid:%d parent[%d]\n",
                       p_regs_get_ret(p_regs),current->comm,current->pid,current->real_parent->pid);

   // Update process
   p_tasks_write_lock(&p_flags);
   if ( (p_tmp = p_find_ed_by_pid(task_pid_nr(current))) != NULL) {
      if (!p_regs_get_ret(p_regs)) {
         // This process is on the ED list - update information!
         p_print_log(P_LKRG_INFO, "Updating ED pid[%d]\n",current->pid);
         p_update_ed_process(p_tmp, current, 0);
      }
#ifdef P_LKRG_TASK_OFF_DEBUG
      p_debug_off_flag_on(p_tmp, 60);
#endif
      p_set_ed_process_on(p_tmp);
   }
   p_tasks_write_unlock(&p_flags);

//   p_ed_enforce_validation();

   return 0;
}


GENERATE_INSTALL_FUNC(sys_unshare)
